package com.example.othree.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.othree.common.PageParam;
import com.example.othree.common.R;
import com.example.othree.entity.*;
import com.example.othree.service.CropsAnalysYearService;
import com.example.othree.service.CropsYieldYearDataService;
import com.example.othree.service.MainCropsHsService;
import com.example.othree.service.MainCropsXtService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zogran
 * @since 2024-12-13
 */
@RestController
@CrossOrigin
@RequestMapping("/api")
public class CropsAnalysYearController {

    @Autowired
    private CropsAnalysYearService cropsAnalysYearService;

    @Autowired
    private MainCropsHsService mainCropsHsService;

    @Autowired
    private MainCropsXtService mainCropsXtService;

    @PostMapping("/casy/create")
    @ApiOperation("新增")
    public R create(@RequestBody CropsAnalysYear cropsAnalysYear){
        return cropsAnalysYearService.save(cropsAnalysYear) ? R.ok() : R.error();
    }

    @PostMapping("/casy/saveBatch")
    @ApiOperation("批量新增")
    public R saveBatch(@RequestBody List<CropsAnalysYear> CropsAnalysYear){
        return cropsAnalysYearService.saveBatch(CropsAnalysYear) ? R.ok() : R.error();
    }

    @GetMapping("/casy/list")
    public List<CropsAnalysYear> list(){
        return cropsAnalysYearService.list();
    }

    @PostMapping("/casy/update")
    @ApiOperation("修改")
    public R update(@RequestBody CropsAnalysYear cropsAnalysYear){
        return cropsAnalysYearService.updateById(cropsAnalysYear) ? R.ok() : R.error();
    }

    @PostMapping("/casy/delete/{id}")
    public R delete(@PathVariable Integer id){
        return cropsAnalysYearService.removeById(id) ? R.ok() : R.error();
    }

    @PostMapping("/casy/listPage")
    @ApiOperation("查询、分页")
    public R listPage(@RequestBody PageParam pageParam){
        HashMap param = pageParam.getParam();
        String county = param.get("county").toString();
        String city = param.get("city").toString();
        String year = param.get("year").toString();

        Page<CropsAnalysYear> page = new Page();
        page.setCurrent(pageParam.getPageNum());
        page.setSize(pageParam.getPageSize());

        LambdaQueryWrapper<CropsAnalysYear> lambdaQueryWrapper = new LambdaQueryWrapper();

        if(StringUtils.isNotBlank(county) && !"null".equals(county)){
            lambdaQueryWrapper.eq(CropsAnalysYear::getCounty, county);
        }
        if(StringUtils.isNotBlank(city) && !"null".equals(city)){
            lambdaQueryWrapper.eq(CropsAnalysYear::getCity, city);
        }
        if(StringUtils.isNotBlank(year) && !"null".equals(year)){
            lambdaQueryWrapper.eq(CropsAnalysYear::getYear, year);
        }

        IPage result = cropsAnalysYearService.PageList(page, lambdaQueryWrapper);

        return R.ok().data("result", result);
    }



    @GetMapping("/crops-analys-year")
    @ApiOperation("获取邢台和衡水所有区县在指定年份的相对产量损失（%）、sum06、AOT40、24_8h_O3（单位:μg/m3）等数据。")
    public R cropsaAnalysYear(@RequestParam("year") String year,
                              @RequestParam("city") String city,
                              @RequestParam("crop") String crop) {

        List<CropsAnalysYearVo> res = cropsAnalysYearService.cropsaAnalysYear(year, city, crop);

        return R.ok().data("data", res);
    }

    @GetMapping("/crops-analys-year-range")
    @ApiOperation("获取邢台或衡水指定区县在指定时间范围内的相对产量损失")
    public R cropsaAnalysYearRange(@RequestParam("city") String city,
                                   @RequestParam("district") String district,
                                   @RequestParam("crop") String crop,
                                   @RequestParam("startYear") String startYear,
                                   @RequestParam("endYear") String endYear) {

        QueryWrapper<CropsAnalysYear> wrapper = new QueryWrapper<>();
        wrapper.eq("city", city);
        wrapper.eq("county", district);
        wrapper.eq("crop", crop);
        wrapper.between("year", startYear, endYear);

        List<CropsAnalysYear> list = cropsAnalysYearService.list(wrapper);

        HashMap<String, TreeMap<String, Float>> res = new HashMap<>();

        String[] features = new String[]{"aot40", "mda8", "sum06", "ryl", "totalProduct"};

        for (String feature : features) {
            TreeMap<String, Float> treeMap = new TreeMap<>();
            if ("aot40".equals(feature)) {
                for (CropsAnalysYear cropsAnalysYear : list) {
                    treeMap.put(cropsAnalysYear.getYear(), cropsAnalysYear.getAot40());
                }
            }
            if ("mda8".equals(feature)) {
                for (CropsAnalysYear cropsAnalysYear : list) {
                    treeMap.put(cropsAnalysYear.getYear(), cropsAnalysYear.getMda8());
                }
            }
            if ("sum06".equals(feature)) {
                for (CropsAnalysYear cropsAnalysYear : list) {
                    treeMap.put(cropsAnalysYear.getYear(), cropsAnalysYear.getSum06());
                }
            }
            if ("ryl".equals(feature)) {
                for (CropsAnalysYear cropsAnalysYear : list) {
                    treeMap.put(cropsAnalysYear.getYear(), cropsAnalysYear.getRyl());
                }
            }
            if ("totalProduct".equals(feature)) {
                for (CropsAnalysYear cropsAnalysYear : list) {
                    if (cropsAnalysYear.getCity().equals("衡水")) {
                        QueryWrapper<MainCropsHs> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("year", cropsAnalysYear.getYear());
                        queryWrapper.like("county", cropsAnalysYear.getCounty());
                        queryWrapper.eq("crops_name", cropsAnalysYear.getCrop());
                        MainCropsHs yearData = mainCropsHsService.getOne(queryWrapper);
                        if (yearData == null) {
                            treeMap.put(cropsAnalysYear.getYear(), null);
                        } else {
                            treeMap.put(cropsAnalysYear.getYear(), Float.valueOf(yearData.getTotalProduct()));
                        }

                    } else {
                        QueryWrapper<MainCropsXt> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("year", cropsAnalysYear.getYear());
                        queryWrapper.like("county", cropsAnalysYear.getCounty());
                        queryWrapper.eq("crops_name", cropsAnalysYear.getCrop());
                        MainCropsXt yearData = mainCropsXtService.getOne(queryWrapper);
                        if (yearData == null) {
                            treeMap.put(cropsAnalysYear.getYear(), null);
                        } else {
                            treeMap.put(cropsAnalysYear.getYear(), Float.valueOf(yearData.getTotalProduct()));
                        }

                    }

                }
            }
            res.put(feature, treeMap);
        }
        return R.ok().data("data", res);
    }



}

